package com.ruoyi.system.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.constant.SysMsgConstans;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.domain.SysOrderDept;
import com.ruoyi.system.domain.SysOrderStrikeInvalid;
import com.ruoyi.system.domain.dto.OrderStrikeWorkTaskResponseDTO;
import com.ruoyi.system.domain.dto.SysOrderResponseDTO;
import com.ruoyi.system.domain.vo.req.personne.PersonneQueryReqVo;
import com.ruoyi.system.domain.vo.resp.UserInfoRespVo;
import com.ruoyi.system.domain.vo.resp.personne.PersonneCountRespVo;
import com.ruoyi.system.domain.vo.resp.personne.PersonneListRespVo;
import com.ruoyi.system.mapper.DataScreeningPersonnelMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.vo.req.order.OrderDataGroupResponseDTO;
import com.ruoyi.system.vo.req.order.OrderResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xdh
 * @title MsgTask
 * @date 2024/7/5 11:10
 * @description TODO
 */
@Configuration
@EnableScheduling
public class MsgTask {

    @Autowired
    private SysOrderStrikeInvalidService sysOrderStrikeInvalidService;

    @Autowired
    private SysMsgService sysMsgService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysOrderStrikeValidService sysOrderStrikeValidService;


    @Autowired
    private  DataScreeningPersonnelMapper dataScreeningPersonnelMapper;
    @Scheduled(cron = "0 0 9 * * ? ")
    private void configureTasks() {
        List<SysOrderResponseDTO> data = sysOrderStrikeInvalidService.listByOrderId();
        if(!data.isEmpty()){

            Map<Integer, Integer> map = data.stream().collect(
                    Collectors.toMap(SysOrderResponseDTO::getDeptId, SysOrderResponseDTO::getCount, (key1, key2) -> key2));
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                List<Integer> userIds =  sysUserMapper.selectUserIdByDeptId(entry.getKey());
                for (Integer userId : userIds) {
                    sysMsgService.userCheck(entry.getKey(),userId,String.format(SysMsgConstans.USER_CHECK_CONTENT, entry.getValue()));
                }

            }
        }
    }



    @Scheduled(cron = "0 0 9 * * 1")
    private void task() {
        List<SysOrderResponseDTO> data = sysOrderStrikeInvalidService.listByOrderId();
        if(!data.isEmpty()){

            Map<Integer, Integer> map = data.stream().collect(
                    Collectors.toMap(SysOrderResponseDTO::getDeptId, SysOrderResponseDTO::getCount, (key1, key2) -> key2));
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                List<Integer> userIds =  sysUserMapper.selectUserIdByDeptId(entry.getKey());
                for (Integer userId : userIds) {
                    sysMsgService.userCheck(entry.getKey(),userId,String.format(SysMsgConstans.USER_CHECK_CONTENT, entry.getValue()));
                }

            }
        }
    }


    @Scheduled(cron = "0 0 0/4 * * ?")
    private void workTask() {
        Date date = new Date();
        String YYYYMMDD = new SimpleDateFormat("yyyy年MM月dd日").format(date);

        //查询市级账户级区级账户
        List<OrderStrikeWorkTaskResponseDTO> orderStrikeWorkTaskResponseDTOS = sysUserMapper.selectCityAndZoneUsers();

        if(!orderStrikeWorkTaskResponseDTOS.isEmpty()){


            //查询市级区级单位
            Map<Integer, List<OrderStrikeWorkTaskResponseDTO>> map = orderStrikeWorkTaskResponseDTOS.stream()
                    .collect(Collectors.groupingBy(OrderStrikeWorkTaskResponseDTO::getDeptLevel));

            List<OrderStrikeWorkTaskResponseDTO> cityUsers = map.get(1);
            if(!cityUsers.isEmpty()){
                Map<Integer, List<OrderStrikeWorkTaskResponseDTO>> collect = cityUsers
                        .stream().collect(Collectors.groupingBy(OrderStrikeWorkTaskResponseDTO::getDeptId));
                //获取市级单位id
                for (Integer cityDeptId : collect.keySet()) {

                    OrderResponseVO data = data(cityDeptId);




//                    //查询核查订单数据
//                    List<SysOrderStrikeInvalid> orders = sysOrderStrikeInvalidService.selectListByDeptId(cityDeptId);
//
//                    //查询有效、无效数据
//                    Map<Integer, List<SysOrderStrikeInvalid>> isValid = orders.stream().collect(Collectors.groupingBy(SysOrderStrikeInvalid::getIsValid));
//
//                    //有效 （被排查人数）
//                    int isValid1 = isValid.get(1).size();
//
//                    //无效
//                    int isValid0 = isValid.get(0).size();

                    //无人机数量
                    Integer droneNum = sysOrderStrikeValidService.selectDroneCountByDeptId(cityDeptId);

                    //重点人员
                    Integer policeNum = sysOrderStrikeValidService.selectPoliceUserCountByDeptId(cityDeptId);

                    //重点人员中持有无人机
                    Integer policeDroneNum = sysOrderStrikeValidService.selectPoliceDroneCountByDeptId(cityDeptId);


                    List<SysOrderResponseDTO> list = dataScreeningPersonnelMapper.selectpersonneListByDeptId(cityDeptId);

                    Map<Integer, List<SysOrderResponseDTO>> collect1 = list.stream().collect(Collectors.groupingBy(SysOrderResponseDTO::getCount));



                    List<OrderStrikeWorkTaskResponseDTO> orderStrikeWorkTaskResponseDTOS1 = collect.get(cityDeptId);
                    for (OrderStrikeWorkTaskResponseDTO orderStrikeWorkTaskResponseDTO : orderStrikeWorkTaskResponseDTOS1) {

                        String msg = "";

                        int total = data.getInValidNum().intValue() + data.getInValidNum().intValue();
                        if(total == 0){
                            continue;

                        }else{
                            msg += String.format(SysMsgConstans.WORK_CITY_CHECK_CONTENT_NODE1, YYYYMMDD, data.getOrderTotal());
                        }

                        if(data.getInValidNum().intValue() > 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE2,data.getInValidNum());
                        }
                        if(data.getValidNum().intValue() > 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE3,data.getValidNum(),data.getValidNum());
                        }

                        if(droneNum.intValue() > 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE4,droneNum.intValue());
                        }

                        if(policeNum.intValue() > 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE5,policeNum.intValue());
                        }

                        if(policeDroneNum.intValue()> 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE6,policeDroneNum.intValue());
                        }
                        int num1 = collect1.getOrDefault(1, new ArrayList<>()).size();
                        int num2 = collect1.getOrDefault(0, new ArrayList<>()).size();

                        if(num1 > 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE7,num1);
                        }

                        if(num2 > 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE8,num2);
                        }
                        msg += SysMsgConstans.WORK_CHECK_CONTENT_NODE9;
                        sysMsgService.workCheck(cityDeptId,orderStrikeWorkTaskResponseDTO.getUserId(),msg);


//                        String msg = String.format(SysMsgConstans.WORK_CITY_CHECK_CONTENT, YYYYMMDD, data.getOrderTotal()
//                                , data.getInValidNum(), data.getValidNum(), data.getValidNum(),droneNum,policeNum,policeDroneNum,
//                                collect1.getOrDefault(1,new ArrayList<>()).size(),collect1.getOrDefault(0,new ArrayList<>()).size());
//                        String msg = String.format(SysMsgConstans.WORK_CITY_CHECK_CONTENT, YYYYMMDD, orders.size()
//                                , isValid0, isValid1, isValid1, droneNum, policeNum, policeDroneNum);

                    }



                }

            }
            //获取区级账户
            List<OrderStrikeWorkTaskResponseDTO> zoneUsers = map.get(2);
            if(!cityUsers.isEmpty()){
                Map<Integer, List<OrderStrikeWorkTaskResponseDTO>> collect = zoneUsers
                        .stream().collect(Collectors.groupingBy(OrderStrikeWorkTaskResponseDTO::getDeptId));
                //获取区级单位id
                for (Integer zoneDeptId : collect.keySet()) {
                    OrderResponseVO data = data(zoneDeptId);




//                    //查询核查订单数据
//                    List<SysOrderStrikeInvalid> orders = sysOrderStrikeInvalidService.selectListByDeptId(cityDeptId);
//
//                    //查询有效、无效数据
//                    Map<Integer, List<SysOrderStrikeInvalid>> isValid = orders.stream().collect(Collectors.groupingBy(SysOrderStrikeInvalid::getIsValid));
//
//                    //有效 （被排查人数）
//                    int isValid1 = isValid.get(1).size();
//
//                    //无效
//                    int isValid0 = isValid.get(0).size();

                    //无人机数量
                    Integer droneNum = sysOrderStrikeValidService.selectDroneCountByDeptId(zoneDeptId);

                    //重点人员
                    Integer policeNum = sysOrderStrikeValidService.selectPoliceUserCountByDeptId(zoneDeptId);

                    //重点人员中持有无人机
                    Integer policeDroneNum = sysOrderStrikeValidService.selectPoliceDroneCountByDeptId(zoneDeptId);


                    List<SysOrderResponseDTO> list = dataScreeningPersonnelMapper.selectpersonneListByDeptId(zoneDeptId);

                    Map<Integer, List<SysOrderResponseDTO>> collect1 = list.stream().collect(Collectors.groupingBy(SysOrderResponseDTO::getCount));



                    List<OrderStrikeWorkTaskResponseDTO> orderStrikeWorkTaskResponseDTOS1 = collect.get(zoneDeptId);
                    for (OrderStrikeWorkTaskResponseDTO orderStrikeWorkTaskResponseDTO : orderStrikeWorkTaskResponseDTOS1) {
                        String msg = "";
                        int total = data.getInValidNum().intValue() + data.getInValidNum().intValue();
                        if( total == 0){
                            continue;

                        }else{
                            msg += String.format(SysMsgConstans.WORK_ZONE_CHECK_CONTENT_NODE1, YYYYMMDD, data.getOrderTotal());
                        }

                        if(data.getInValidNum().intValue() > 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE2,data.getInValidNum());
                        }
                        if(data.getValidNum().intValue() > 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE3,data.getValidNum(),data.getValidNum());
                        }

                        if(droneNum.intValue() > 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE4,droneNum.intValue());
                        }

                        if(policeNum.intValue() > 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE5,policeNum.intValue());
                        }

                        if(policeDroneNum.intValue()> 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE6,policeDroneNum.intValue());
                        }
                        int num1 = collect1.getOrDefault(1, new ArrayList<>()).size();
                        int num2 = collect1.getOrDefault(0, new ArrayList<>()).size();

                        if(num1 > 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE7,num1);
                        }

                        if(num2 > 0){
                            msg += String.format(SysMsgConstans.WORK_CHECK_CONTENT_NODE8,num2);
                        }
                        msg += SysMsgConstans.WORK_CHECK_CONTENT_NODE9;
                        sysMsgService.workCheck(zoneDeptId,orderStrikeWorkTaskResponseDTO.getUserId(),msg);

                    }

                }

            }
        }
//        List<SysOrderResponseDTO> data = sysOrderStrikeInvalidService.listByOrderId();
//        if(!data.isEmpty()){
//
//            Map<Integer, Integer> map = data.stream().collect(
//                    Collectors.toMap(SysOrderResponseDTO::getDeptId, SysOrderResponseDTO::getCount, (key1, key2) -> key2));
//            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
//                List<Integer> userIds =  sysUserMapper.selectUserIdByDeptId(entry.getKey());
//                for (Integer userId : userIds) {
//                    sysMsgService.userCheck(entry.getKey(),userId,String.format(SysMsgConstans.USER_CHECK_CONTENT, entry.getValue()));
//                }
//
//            }
//        }
    }

    @Autowired
    private SysOrderDeptService sysOrderDeptService;

    public OrderResponseVO data(Integer deptId) {


        OrderResponseVO orderResponseVO = new OrderResponseVO();
        Integer orderTotal = sysOrderDeptService.count(new LambdaQueryWrapper<SysOrderDept>()
                .eq(SysOrderDept::getStatus, 1).eq(SysOrderDept::getDeptId, deptId));
        orderResponseVO.setOrderTotal(orderTotal);

        Integer inStrikeNum = sysOrderDeptService.count(new LambdaQueryWrapper<SysOrderDept>()
                .eq(SysOrderDept::getStatus, 1).eq(SysOrderDept::getDeptId, deptId).eq(SysOrderDept::getOrderStatus, 2));

        orderResponseVO.setInStrikeNum(inStrikeNum);
        Integer StrikeNum = sysOrderDeptService.count(new LambdaQueryWrapper<SysOrderDept>()
                .eq(SysOrderDept::getStatus, 1).eq(SysOrderDept::getDeptId, deptId).eq(SysOrderDept::getOrderStatus, 3));
        orderResponseVO.setStrikeNum(StrikeNum);


        List<SysOrderResponseDTO> validNum = sysOrderStrikeInvalidService.countBySql(deptId.longValue());

        Map<Integer, Integer> map = validNum.stream().collect(Collectors.toMap(SysOrderResponseDTO::getDeptId, SysOrderResponseDTO::getCount, (oldValue, newValue) -> newValue));
        orderResponseVO.setValidNum(map.getOrDefault(1,0));
        orderResponseVO.setInValidNum(map.getOrDefault(0,0));

//        int invalidNum = sysOrderStrikeInvalidService.count(new LambdaQueryWrapper<SysOrderStrikeInvalid>()
//                .eq(SysOrderStrikeInvalid::getStatus, 1).eq(SysOrderStrikeInvalid::getDeptId, dept.getDeptId()).eq(SysOrderStrikeInvalid::getIsValid, 0));



        //orderResponseVO.setKvs();




        return orderResponseVO;
    }


}
